<template>
	<div>
		<el-table :data="list" style="width: 100%">
			<el-table-column prop="id" label="ID" />
			<el-table-column prop="name" label="姓名" />
			<el-table-column prop="age" label="年龄" />
			<el-table-column prop="tel" label="电话" />
			<el-table-column prop="sex" label="性别" />
			<el-table-column label="操作">
				<template #default="scope">
					<el-button type="primary" @click="handleModify(scope.row)">编辑</el-button>
				</template>
			</el-table-column>
		</el-table>

		<el-dialog v-model="visible" title="修改">
			<el-row style="margin: 10px 0;">
				<el-col :span="2">姓名:</el-col>
				<el-col :span="20">
					<el-input v-model="item.name"></el-input>
				</el-col>
			</el-row>
			<el-row style="margin: 10px 0;">
				<el-col :span="2">电话:</el-col>
				<el-col :span="20">
					<el-input v-model="item.tel"></el-input>
				</el-col>
			</el-row>
			<el-row style="margin: 10px 0;">
				<el-col :span="2">年龄:</el-col>
				<el-col :span="20">
					<el-input v-model="item.age"></el-input>
				</el-col>
			</el-row>
			<el-row style="margin: 10px 0;">
				<el-col :span="2">性别:</el-col>
				<el-col :span="20">
					<el-select v-model="item.sex">
						<el-option label="男" value="男"></el-option>
						<el-option label="女" value="女"></el-option>
					</el-select>
				</el-col>
			</el-row>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="visible = false">取消</el-button>
					<el-button type="primary" @click="handleEdit">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import axios from 'axios'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
interface ListState {
	"name": string
	"age": string
	"sex": '男' | '女'
	"tel": string
	"id": string
}

const list = ref<ListState[]>([]);
const visible = ref(false)
const item = ref<ListState>({
	id: '',
	name: '',
	age: '',
	sex: '男',
	tel: ''
})
const handleModify = (row: ListState) => {
	visible.value = true
	item.value = { ...row }
}

const handleEdit = async () => {
	visible.value = false
	const resp = await axios.post('/api/edit', { item: item.value });
	const { code, message } = resp.data;
	if (code === 200) {
		getList();
		ElMessage({
			message,
			type: 'success',
		})
	} else {
		ElMessage({
			message,
			type: 'error',
		})
	}
}
const getList = async () => {
	const resp = await axios.get('/api/list')
	list.value = resp.data.data
}
onMounted(() => {
	getList()
})
</script>